<!DOCTYPE html>
<html>

<head>test promise</head>

<body>
    <div>
        <button onclick="triggerAsync()">执行一个异步方法</button>
        <button onclick="doAsSync()">使用Async异步变同步</button>
        <button onclick="doGen()">使用Generator异步变同步</button>
        <button onclick="doNet()">网络访问百度</button>
        <button onclick="doMockSleep()">模拟sleep</button>
    </div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
    // 模拟一个异步操作
    // 传递进来的函数要2秒之后才能执行
    function delayedFunc(callback) {
        console.log("异步方法调用开始");
        setTimeout(() => {
            console.log("异步主业务逻辑执行完毕");
            callback();
        }, 2000);
        return 1;
    }

    // 触发一个异步函数，要执行回调
    function triggerAsync() {
        let a = () => {
            console.log("回调函数被执行");
        };
        delayedFunc(a);
    }

    function delayedFunc2(fn) {
        return new Promise((resolve) => {
            // 可以用此特性模拟Sleep
            setTimeout(resolve, 2000);
            fn();
        });
    }

    async function wrapperSync() {
        let a = () => {
            console.log("回调函数a被执行");
            return 100;
        };
        let b = () => {
            console.log("回调函数b被执行");
            return 200;
        };
        await delayedFunc2(a);
        await delayedFunc2(b);
    }

    function doAsSync() {
        let p = wrapperSync();
        p.then((i) => {
            console.log("promise 执行完毕=" + i);
        }).then((i) => {
            console.log("promise 执行完毕=" + i);
        });
    }

    function* wrapperGen() {
        let a = () => {
            console.log("回调函数a被执行");
            return 100;
        };
        let b = () => {
            console.log("回调函数b被执行");
            return 200;
        };
        yield delayedFunc(a);
        yield delayedFunc(b);
        return 100;
    }

    function doGen() {
        let m = wrapperGen();
        let ret = m.next();
        if (ret.value == 3) {
            console.log("ret.value=" + ret.value);
            m.next();
        } else {
            // 第一步执行出错，就不能走下文
            console.log("错了" + ret.value);
        }
    }

    async function asyncNetAccess() {
        // await axios.get("https://portal.haierfinancial.com:18607/my_haier", {
        // });
        await axios.get("https://10.164.15.20/core/auth/login/");
    }

    function doNet() {
        let p = asyncNetAccess();
        p.then((i) => {
            console.log("resp=" + i);
        }).then((i) => {
            console.log("resp=" + i);
        });
    }

    function sleep(interval) {
        return new Promise(resolve => {
            setTimeout(resolve, interval);
        })
    }

    // 用法
    async function doMockSleep() {
        console.log("函数进入");
        await sleep(6000);
        console.log("函数退出");
    }


</script>